//
//  FQDLabVoteDetailViewController.m
//  FakeQDaily
//
//  Created by mewxiv on 9/18/16.
//  Copyright © 2016 Xensius. All rights reserved.
//

#import "FQDLabVoteDetailViewController.h"
#import "FQDLabVoteResultViewController.h"
#import "FQDCommentViewController.h"
#import "FQDLabTitleImageCell.h"
#import "FQDLabFeedCell.h"
#import "FQDSeparatorCell.h"
#import "FQDLabOptionCell.h"
#import "FQDLabVoteButtonCell.h"
#import "FQDDetailToolBar.h"
#import "FQDDetailToolBarButton.h"
#import "MBProgressHUD+FQDExtension.h"
#import "FQDLabFeedCellItem.h"
#import "QDailyAPI.h"
#import "FQDRestModel.h"

#import "Masonry.h"

static CGSize const kArticleToolBarSize = (CGSize){136.0f, 69.0f};

@interface FQDLabVoteDetailViewController () <UICollectionViewDelegate,
                                              UICollectionViewDataSource,
                                              UICollectionViewDelegateFlowLayout>

// 返回按钮
@property (nonatomic, strong) UIButton *backButton;
// 右下角工具栏
@property (nonatomic, strong) FQDDetailToolBar *detailToolBar;
// 评论按钮
@property (nonatomic, strong) FQDDetailToolBarButton *commentButton;
// 顶部标题单元格，弹幕显示在上面
@property (nonatomic, weak) FQDLabTitleImageCell *headCell;
// 计算size的单元格
@property (nonatomic, strong) FQDLabFeedCell *sizingCell;
// 所有内容都显示在collectionView内
@property (nonatomic, strong) UICollectionView *collectionView;
// 当前的问题
@property (nonatomic, strong) FQDLabQuestion *question;
// 选项列表
@property (nonatomic, strong) NSArray *options;
// 已经选择的选项
@property (nonatomic, strong) NSMutableSet *selectedIndexPaths;

@end

@implementation FQDLabVoteDetailViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    self.selectedIndexPaths = [NSMutableSet set];
    [self setupCollectionView];
    [self setupDetailToolbar];
    [self updateDetailToolbar];
    [self loadPaperDetail];
    
}

- (void)setupCollectionView
{
    UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
    flowLayout.minimumLineSpacing = 10.0f;
    flowLayout.minimumInteritemSpacing = 0;
    
    self.collectionView = [[UICollectionView alloc] initWithFrame:self.view.bounds collectionViewLayout:flowLayout];
    self.collectionView.backgroundColor = [UIColor whiteColor];
    self.collectionView.contentInset = UIEdgeInsetsMake(0, 0, 80.0f, 0);
    self.collectionView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
    self.collectionView.delegate = self;
    self.collectionView.dataSource = self;
    [self.view addSubview:self.collectionView];
    
    [self.collectionView registerClass:[FQDLabTitleImageCell class]
            forCellWithReuseIdentifier:[FQDLabTitleImageCell reuseId]];
    [self.collectionView registerClass:[FQDLabFeedCell class]
            forCellWithReuseIdentifier:[FQDLabFeedCell reuseId]];
    [self.collectionView registerClass:[FQDSeparatorCell class]
            forCellWithReuseIdentifier:[FQDSeparatorCell reuseId]];
    [self.collectionView registerClass:[FQDLabOptionCell class]
            forCellWithReuseIdentifier:[FQDLabOptionCell reuseId]];
    [self.collectionView registerClass:[FQDLabVoteButtonCell class]
            forCellWithReuseIdentifier:[FQDLabVoteButtonCell reuseId]];
}

- (void)setupDetailToolbar
{
    UIImage *backImage = [UIImage imageNamed:@"navigation_back_round_normal"];
    self.backButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [self.backButton setImage:backImage forState:UIControlStateNormal];
    [self.view addSubview:self.backButton];
    
    [self.backButton addTarget:self
                        action:@selector(goBack:)
              forControlEvents:UIControlEventTouchUpInside];
    
    WeakSelf;
    [self.backButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(weakSelf.view).offset(14);
        make.bottom.equalTo(weakSelf.view).offset(-4);
    }];
    
    UIImage *commentImage = [UIImage imageNamed:@"toolbarComment"];
    FQDDetailToolBarButton *commentButton =
    [FQDDetailToolBarButton buttonWithIcon:commentImage
                                detailText:@""
                                    target:self
                                    action:@selector(showCommentView:)];
    self.commentButton = commentButton;
    
    UIImage *shareImage = [UIImage imageNamed:@"toolbarShare"];
    FQDDetailToolBarButton *shareButton =
    [FQDDetailToolBarButton buttonWithIcon:shareImage
                                detailText:@""
                                    target:self
                                    action:@selector(shareThisArticle:)];
    
    NSArray *barButtons = @[commentButton, shareButton];
    
    self.detailToolBar = [[FQDDetailToolBar alloc] initWithBarButtons:barButtons];
    [self.view addSubview:self.detailToolBar];
    
    [self.detailToolBar mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(weakSelf.view);
        make.bottom.equalTo(weakSelf.view);
        make.size.mas_equalTo(kArticleToolBarSize);
    }];
}

- (void)updateDetailToolbar
{
    FQDPost *post = self.labFeedCellItem.feed.post;
    NSInteger commentCount = post.comment_count;
    NSString *commentNumStr = (commentCount == 0) ? @"" : [@(commentCount) stringValue];
    self.commentButton.detailTextLabel.text = commentNumStr;
}

- (void)loadPaperDetail
{
    WeakSelf;
    NSString *qdID = self.labFeedCellItem.feed.post.ID;
    [[QDailyAPI sharedAPI] getLabPaperDetail:qdID completion:^(id responseObject, NSError *error) {
        id response = responseObject[@"response"];
        NSArray *questions = [NSArray yy_modelArrayWithClass:[FQDLabQuestion class]
                                                              json:response[@"questions"]];
        NSString *feedImage = response[@"image"];
        NSNumber *feedType = response[@"type"];
        FQDPost *post = [FQDPost yy_modelWithJSON:response[@"post"]];
        self.labFeedCellItem.feed.image = feedImage;
        self.labFeedCellItem.feed.type = [feedType integerValue];
        self.labFeedCellItem.feed.post = post;
        
        FQDLabQuestion *question = questions[0];
        if (question) {
            weakSelf.question = question;
            NSArray *options = question.options;
            weakSelf.options = options;
            [weakSelf.collectionView reloadData];
        }
    }];
}

- (void)sendVoteResult
{
    if ([self.selectedIndexPaths count] <= 0) {
        return;
    }
    NSMutableArray *optionIds = [NSMutableArray array];
    for (NSIndexPath *indexPath in self.selectedIndexPaths) {
        FQDLabOpinion *option = self.options[indexPath.item];
        [optionIds addObject:option.ID];
    }
    FQDFeed *feed = self.labFeedCellItem.feed;
    NSString *paperId = feed.post.ID;
    
    WeakSelf;
    [MBProgressHUD showLoadingAnim];
    [[QDailyAPI sharedAPI] sendLabVoteResultWithOptionIds:optionIds paperId:paperId
     completion:^(id responseObject, NSError *error) {
         [MBProgressHUD hideLoadingAnim];
         
         NSNumber *status = [responseObject valueForKeyPath:@"meta.status"];
         if ([status integerValue] == 200) {
             id response = responseObject[@"response"];
             NSNumber *commentCount = response[@"comment_count"];
             FQDLabOpinion *option = [FQDLabOpinion yy_modelWithJSON:response[@"option"]];
             NSArray *attitudes = [NSArray yy_modelArrayWithClass:[FQDLabVoteAttitude class]
                                                            json:response[@"everyones_attitude"]];
             for (FQDLabVoteAttitude *attitude in attitudes) {
                 for (FQDLabOpinion *option in weakSelf.options) {
                     if ([attitude.content isEqualToString:option.content]) {
                         attitude.optionID = option.ID;
                     }
                 }
             }
             
             [self clearVoteChoices];
             
             FQDLabVoteResultViewController *lvrVC = [[FQDLabVoteResultViewController alloc] init];
             lvrVC.selectedOptionIds = optionIds;
             lvrVC.option = option;
             lvrVC.post = feed.post;
             lvrVC.attitudes = attitudes;
             lvrVC.commentCount = [commentCount integerValue];
             [self.navigationController pushViewController:lvrVC animated:YES];
             
         }
    }];
}

- (void)clearVoteChoices
{
    [self.selectedIndexPaths removeAllObjects];
    [self.collectionView reloadData];
}

#pragma mark - Event response
- (void)goBack:(id)sender
{
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)showCommentView:(id)sender
{
    FQDFeed *feed = self.labFeedCellItem.feed;
    FQDCommentViewController *commentVC = [[FQDCommentViewController alloc] init];
    commentVC.post = feed.post;
    [self.navigationController pushViewController:commentVC animated:YES];
}

- (void)shareThisArticle:(id)sender
{
    
}

#pragma mark - UICollectionViewDataSource
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
    return 5;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    if (section == 3) {
        return [self.options count];
    } if (section == 4) {
        return ([self.options count] > 0) ? 1 : 0;
    } else {
        return 1;
    }
    return 0;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    UICollectionViewCell *cell;
    if (indexPath.section == 0) {
        cell = [collectionView dequeueReusableCellWithReuseIdentifier:[FQDLabTitleImageCell reuseId]
                                                         forIndexPath:indexPath];
        self.headCell = (FQDLabTitleImageCell *)cell;
        self.headCell.post = self.labFeedCellItem.feed.post;
        
    } else if (indexPath.section == 1) {
        FQDLabFeedCell *labFeedCell = (FQDLabFeedCell *)
        [collectionView dequeueReusableCellWithReuseIdentifier:[FQDLabFeedCell reuseId]
                                                  forIndexPath:indexPath];
        
        labFeedCell.showContentImage = NO;
        labFeedCell.cellItem = self.labFeedCellItem;
        cell = labFeedCell;
        
    } else if (indexPath.section == 2) {
        cell = [collectionView dequeueReusableCellWithReuseIdentifier:[FQDSeparatorCell reuseId]
                                                         forIndexPath:indexPath];
        cell.backgroundColor = RGB(242, 242, 242);
    } else if (indexPath.section == 3) {
        cell = [collectionView dequeueReusableCellWithReuseIdentifier:[FQDLabOptionCell reuseId]
                                                         forIndexPath:indexPath];
        
        FQDLabOptionCell *optionCell = (FQDLabOptionCell *)cell;
        optionCell.option = self.options[indexPath.item];
        optionCell.canChooseMulti = (self.question.genre == FQDLabQuestionGenreMulti);
        optionCell.isChoosed = [self.selectedIndexPaths containsObject:indexPath];
    } else if (indexPath.section == 4) {
        cell = [collectionView dequeueReusableCellWithReuseIdentifier:[FQDLabVoteButtonCell reuseId]
                                                         forIndexPath:indexPath];
        if ([self.selectedIndexPaths count] > 0) {
            cell.alpha = 1;
        } else {
            cell.alpha = 0.6f;
        }
        
        FQDLabVoteButtonCell *voteCell = (FQDLabVoteButtonCell *)cell;
        [voteCell.voteButton addTarget:self action:@selector(sendVoteResult) forControlEvents:UIControlEventTouchUpInside];
    }
    
    return cell;
}

#pragma mark - UICollectionViewDelegateindexPath
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 3) {
        if (self.question.genre == FQDLabQuestionGenreSingle) {
            [self.selectedIndexPaths removeAllObjects];
            [self.selectedIndexPaths addObject:indexPath];
        } else {
            if ([self.selectedIndexPaths containsObject:indexPath]) {
                [self.selectedIndexPaths removeObject:indexPath];
            } else {
                [self.selectedIndexPaths addObject:indexPath];
            }
        }
        [collectionView reloadData];
    } else if (indexPath.section == 4) {
        [self sendVoteResult];
    }
}

#pragma mark - UIScrollViewDelegate
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    if (self.headCell) {
        CGFloat maxHeight = [FQDLabTitleImageCell cellHeight];
        CGFloat offset = scrollView.contentOffset.y;
        if (maxHeight - offset >= 0) {
            CGRect frame = self.headCell.frame;
            frame.origin.y = offset;
            frame.size.height = maxHeight - offset;
            self.headCell.frame = frame;
        }
    }
}

#pragma mark - UICollectionViewDelegateFlowLayout
- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section
{
    if (section == 3) {
        return UIEdgeInsetsMake(10.0f, 0, 10.0f, 0);
    }
    return UIEdgeInsetsZero;
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
    CGSize size;
    CGFloat viewWidth = collectionView.frame.size.width;
    if (indexPath.section == 0) {
        size = CGSizeMake(viewWidth, [FQDLabTitleImageCell cellHeight]);
    } else if (indexPath.section == 1) {
        size = [self collectionView:collectionView layout:collectionViewLayout sizeForLabFeedCellAtIndexPath:indexPath];
    } else if (indexPath.section == 2) {
        size = CGSizeMake(viewWidth, 5.0f);
    } else if (indexPath.section == 3){
        size = CGSizeMake(viewWidth, 80.0f);
    } else if (indexPath.section == 4) {
        size = CGSizeMake(viewWidth, 50.0f);
    }
    return size;
}


- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForLabFeedCellAtIndexPath:(NSIndexPath *)indexPath
{
    if (!self.sizingCell) {
        CGFloat itemWidth = collectionView.frame.size.width;
        self.sizingCell = (self.sizingCell) ? : [[FQDLabFeedCell alloc] init];
        self.sizingCell.cellItem = self.labFeedCellItem;
        self.sizingCell.showContentImage = NO;
        CGSize cellSize = [self.sizingCell systemLayoutSizeFittingSize:UILayoutFittingCompressedSize];
        cellSize.width = itemWidth;
        self.sizingCell.frame = (CGRect){CGPointZero, cellSize};
    }
    return self.sizingCell.frame.size;
}

@end
